//
//  UITextView+Emoticon.swift
//  表情键盘
//
//  Created by Bingo on 15/11/6.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit

extension UITextView{


    func emoticonText() -> String{
        var text = ""
        
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, Range, _) -> Void in
            
            if let attchment = dict["NSAttachment"]as?LLTextAttachment{
            
                text += attchment.name!
            }else{
                let str = (self.attributedText.string as NSString).substringWithRange(Range)
                
                text += str
            }
        }
        return text
    }
    
    
    
    func insertEmoticon(emoticon:LLEmoticon){
        if emoticon.removeEmoticon{
        
            deleteBackward()
        }
        
        if let emoji = emoticon.emoji{
            
            insertText(emoji)
        }
       
        if let pngPath = emoticon.pngPath {
        
//        let attachment = LLTextAttachment()
//        
//        let image = UIImage(contentsOfFile: pngPath)
//        
//        attachment.image = image
//        
//        attachment.name = emoticon.chs
//        
//        let height = font?.lineHeight ?? 10
//        
//        attachment.bounds = CGRect(x: 0, y: -(height * 0.25), width: height, height: height)
//        
//        let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//        
//        attrString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
        
        let attrString = emoticon.emoticonToAttrString(font!)
            
        let oldAttrString = NSMutableAttributedString(attributedString:attributedText)
        
        let oldSelecteRange = selectedRange
        
        oldAttrString.replaceCharactersInRange(oldSelecteRange, withAttributedString: attrString)
        
        attributedText = oldAttrString
        
        selectedRange = NSRange(location: oldSelecteRange.location + 1, length: 0)
            
            delegate?.textViewDidChange?(self)
            
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
        
         }
     }
}
